package uk.ac.lkl.lpp.xml;
/*
 * Converts .lpp date files using xslt stylesheets
 */
import javax.xml.transform.*;

import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
//import junit.framework.*;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Hashtable;

import uk.ac.lkl.common.util.Resources;
import uk.ac.lkl.lpp.PedagogyPlan;

public class XSLTConvertor{
	private static TransformerFactory factory ;
	private static Transformer trans;
	
	
	public static void convert(File xml,File xslt,File out,Hashtable pars)throws TransformerException,IOException{
			Source xmlSource=new StreamSource(xml);
			Source xsltSource=new StreamSource(xslt);
			Result result=new StreamResult(out);
			factory = TransformerFactory.newInstance();
			trans = factory.newTransformer(xsltSource);
			setParameters(trans,pars);
			trans.transform(xmlSource, result);		
	}
	
	public static void convert(File xml, InputStream xslt,File out,Hashtable pars)throws TransformerException,IOException{		
			Source xmlSource=new StreamSource(xml);
			Source xsltSource=new StreamSource(xslt);
			Result result=new StreamResult(out);
			factory = TransformerFactory.newInstance();
			trans = factory.newTransformer(xsltSource);
			setParameters(trans,pars);
			trans.transform(xmlSource, result);
	}
	
	public static void convertFromResource(String xml,String xslt,String out,Hashtable pars)throws TransformerException,IOException{
	
			Source xmlSource=new StreamSource(new File(xml));
			//Source xsltSource=new StreamSource(new File(xslt).getClass().getResourceAsStream(xslt));
			
			InputStream xslIS = Resources.getResourceInputStream(xslt);			
			
			Source xsltSource=new StreamSource(xslIS);
			Result result=new StreamResult(new File(out));
			
			factory = TransformerFactory.newInstance();
			trans = factory.newTransformer(xsltSource);
			setParameters(trans,pars);
			trans.transform(xmlSource, result);

	}
	public static void setParameters(Transformer t,Hashtable h){
		   for (Enumeration e = h.keys(); e.hasMoreElements();)
		   {
			   String par=(String)e.nextElement();
			   String val=(String)h.get((Object)par);
			   //String str = (String) h.get( e.nextElement());
			   t.setParameter(par, val);
		   }
	}
	

}